<template>
  <a-modal
    :title="modalTitle"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleModalOk"
    @cancel="handleModalCancel"
    :width="680"
    okText="确定"
    cancelText="取消">

    <a-form-model ref="form" :model="formData" :rules="rules" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }">
      <a-form-model-item label="变量集" prop="setCode">
        <a-input v-model="formData.setCode" placeholder="请输入变量集名称" :disabled="isEdit" />
      </a-form-model-item>

      <a-form-model-item label="描述" prop="description">
        <a-textarea v-model="formData.description" placeholder="请输入详细描述信息" :rows="4" :maxlength="500" show-count />
      </a-form-model-item>

      <a-form-model-item label="标签" prop="tags">
        <div>
          <div
            v-for="(tag, index) in formData.tags"
            :key="index"
            style="display: flex; align-items: center; margin-bottom: 8px;">
            <a-input v-model="formData.tags[index]" placeholder="请输入标签名称" style="flex: 1; margin-right: 8px;" />
            <a-button
              v-if="formData.tags.length > 1"
              type="danger"
              size="small"
              icon="minus"
              @click="removeTag(index)"
              title="删除标签" />
            <a-button
              v-if="index === formData.tags.length - 1"
              type="primary"
              size="small"
              icon="plus"
              @click="addTag"
              title="添加标签"
              style="margin-left: 4px;" />
          </div>
          <div style="margin-top: 8px; font-size: 12px; color: #666;">
            <a-icon type="info-circle" /> 可添加多个标签，用于分类和检索
          </div>
        </div>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import { getBizCreate, getBizUpdate, getBizDetail } from '@/api/creditSetting'
import { mapGetters } from 'vuex'

export default {
  name: 'CreditSettingModal',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    currentRecord: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      confirmLoading: false,
      formData: {
        setCode: '',
        description: '',
        tags: [''],
        createdBy: '',
      },
      rules: {
        setCode: [
          { required: true, message: '请输入变量集', trigger: 'blur' },
          { min: 2, max: 50, message: '变量集长度在 2 到 50 个字符', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请输入描述', trigger: 'blur' },
          { min: 2, max: 500, message: '描述长度在 2 到 500 个字符', trigger: 'blur' },
        ],
        tags: [
          { validator: this.validateTags, trigger: 'blur' },
        ],
      },
    }
  },
  computed: {
    ...mapGetters(['nickname']),
    modalTitle() {
      return this.isEdit ? '编辑变量集' : '新增变量集'
    },
  },
  watch: {
    visible(newVal) {
      if (newVal && this.isEdit && this.currentRecord) {
        this.loadEditData()
      } else if (newVal && !this.isEdit) {
        this.resetForm()
      }
    }
  },
  methods: {
    loadEditData() {
      // 调用详情接口获取完整数据
      getBizDetail({ setCode: this.currentRecord.setCode })
        .then((res) => {
          if (res.code === 0 && res.data) {
            this.formData = {
              setCode: res.data.setCode || '',
              description: res.data.description || '',
              tags: res.data.tags ? res.data.tags.split(',').map(tag => tag.trim()) : [''],
              createdBy: res.data.createdBy || '',
            }
          } else {
            this.$message.error(res.message || '获取详情失败')
          }
        })
        .catch((error) => {
          console.error('获取详情失败:', error)
          this.$message.error('获取详情失败，请稍后重试')
        })
    },
    resetForm() {
      this.formData = {
        setCode: '',
        description: '',
        tags: [''],
        createdBy: '',
      }
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.clearValidate()
        }
      })
    },
    validateTags(rule, value, callback) {
      const validTags = this.formData.tags.filter(tag => tag && tag.trim())
      if (validTags.length === 0) {
        callback(new Error('请至少输入一个标签'))
      } else {
        callback()
      }
    },
    handleModalOk() {
       this.$refs.form.validate(valid => {
         if (!valid) {
           return
         }

         this.confirmLoading = true
         const params = {
           ...this.formData,
           tags: this.formData.tags.filter(tag => tag && tag.trim()).join(','),
           createdBy: this.isEdit ? this.formData.createdBy : this.nickname,
         }

         if (this.isEdit && this.currentRecord) {
           params.id = this.currentRecord.id
         }

         const apiMethod = this.isEdit ? getBizUpdate : getBizCreate

         apiMethod(params)
           .then((res) => {
             if (res.code === 0) {
               this.$message.success(this.isEdit ? '编辑成功' : '新增成功')
               this.$emit('success')
               this.handleModalCancel()
             } else {
               this.$message.error(res.message || (this.isEdit ? '编辑失败' : '新增失败'))
             }
           })
           .catch((error) => {
             console.error('操作失败:', error)
             this.$message.error(this.isEdit ? '编辑失败，请稍后重试' : '新增失败，请稍后重试')
           })
           .finally(() => {
             this.confirmLoading = false
           })
       })
     },
    handleModalCancel() {
      this.$emit('cancel')
      this.confirmLoading = false
      this.resetForm()
    },
    addTag() {
      this.formData.tags.push('')
    },
    removeTag(index) {
      if (this.formData.tags.length > 1) {
        this.formData.tags.splice(index, 1)
      }
    },
  }
}
</script>
